package com.vdongchina.miniapp.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Copyright (C)
 * FileName: HexSign
 * Author:   maokai
 * Date:     2021/8/13 10:59
 * Description: 回调签名验证
 */
public class CallBackSign {
    public static String digest(Map<String, Object> data) {
        String plainText = messageData(data);
        // 获取指定摘要算法的messageDigest对象
        MessageDigest messageDigest = null;
        try {
                messageDigest = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        // 调用digest方法，进行加密操作plainText
        byte[] cipherBytes = messageDigest.digest( plainText.getBytes());
        return encodeHexString(cipherBytes);
    }

    public static String messageData(Map<String, Object> data) {
        if (MapUtils.isEmpty(data)) {
            return "";
        }
        List<String> keys = Lists.newLinkedList();
        Iterator<Map.Entry<String, Object>> iterator = data.entrySet().iterator();

        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            if ("sign".equals(key)) {
                continue;
            }
            if ("type".equals(key)) {
                continue;
            }
            if ("msg_signature".equals(key)) {
                continue;
            }
            String value = String.valueOf(next.getValue());
            keys.add(value);
        }
        List<Object> collect = keys.stream().sorted().collect(Collectors.toList());
        StringBuilder builder = new StringBuilder();
        for (Object value : collect) {
            builder.append(value);
        }
//        String joinStr = String.join("", collect);
        return builder.toString();
    }

    private static String encodeHexString(byte[] md5Bytes) {
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

}
